<template>
  <el-button v-bind="props" icon="Checked" @click="submitForm" v-show="props.show">{{props.label}}</el-button>
</template>

<script lang="ts" setup>
import {getCurrentInstance, onMounted, onUnmounted, ref,inject,computed} from 'vue';
import eventBus from '@/event/eventBus';
import {
  executeQueryKey,
  loadingKey,
  showDialogKey,
  validateFormKey,
  insertOrUpdateFlagKey,
  clearSelectKey
} from "../../../config/app.keys";
import {replaceDynamicVar} from '@/api/tool/replacevar'
import {listInterfaceAll,convert2ApiJson,doRequest} from '@/api/business/interface'
import {ElMessage} from "element-plus";
import { formModeKey } from '@/components/form/state.key';
interface Props {
  size?:string
  type?:string
  plain?:boolean
  text?:boolean
  bg?:boolean
  link?:boolean
  round?:boolean
  circle?:boolean
  loading?:boolean
  disabled?:boolean
  autofocus?:boolean
  formData?:object
  id?:string,
  label?: string,
  //新增操作数据
  addoperationdata:object,
  //更新操作数据
  updateoperationdata:object,
  research:boolean,
  bindButton?:string,//绑定查询按钮
  closeDialog:boolean,//提交后关闭弹窗
  bindDialog?:string
  show?:boolean,//是否显示
}
const props = withDefaults(defineProps<Props>(), {
  label: '提交',
  type:"primary",
  show:true,
})

const {proxy} = getCurrentInstance();
const insert=ref(false)//新增或修改标志
const id = ref(0) //记录id
const formMode = inject(formModeKey)
const cMode = computed<FormFieldMode>(() => {
  if (props.mode) {
    return props.mode
  }
  if (formMode?.value) {
    return formMode.value
  }
  return "edit"
})
function submitForm() {
  // 只有在 edit 模式下才执行删除操作
  if (cMode.value !== 'edit') {
    return;
  }
  submitData();
}

/**
 * 调用api接口
 * @param operationdata
 * @param insertFlag
 */
async function callApi(operationdata,insertFlag) {
//替换变量值
  let opertionParameter = JSON.stringify(operationdata.parameterList);
  let contextMap = new Map();
  console.log('props.formData:' + JSON.stringify(props.formData))
  //如果是更新，则添加id
  if (!insertFlag) {
    contextMap.set('id', id.value);
  }
  let replaceParameters = replaceDynamicVar(props.formData, contextMap, opertionParameter)

  //将replaceParameters转换为json对象
  let jsonParameters = JSON.parse(replaceParameters);
  //调用API
  //改变装载状态
  eventBus.$emit(props.id + "_" + loadingKey, true);
  //根据接口编码查询接口信息
  let interfaceParam = {"interfaceCode": operationdata.interfaceCode};
  let interfaceInfo = await listInterfaceAll(interfaceParam);
  if (interfaceInfo.code === 200) {
    //调用接口
    let commitParameter = convert2ApiJson(jsonParameters)
    let apiParameter = {};

    //判断接口为get,且不是通用接口时，则拼接到后面
    if (interfaceInfo.data[0].interfaceMethod == 'GET') {
      apiParameter = commitParameter;
      //尝试替换url中的变量
      interfaceInfo.data[0].interfaceUrl = replaceDynamicVar(props.formData, contextMap, interfaceInfo.data[0].interfaceUrl);
    } else {
      apiParameter = commitParameter;
    }
    let res = await doRequest(interfaceInfo.data[0], apiParameter);

    if (res.code === 200) {
      if (insertFlag) {
        proxy.$modal.msgSuccess("新增成功");
      } else {
        proxy.$modal.msgSuccess("修改成功");
      }
      if (props.closeDialog && props.bindDialog) {
        eventBus.$emit(props.bindDialog + "_" + showDialogKey, {show: false, form:{}, title: '新增'})
      }
      if (props.research && props.bindButton) {
        eventBus.$emit(props.bindButton + "_" +executeQueryKey,{id:props.id})
      }
    } else {
      ElMessage.error(res.msg || '操作失败！')
    }
  }
}
  /**
   * 提交数据
   */
  function submitData() {
      if (!insert.value) {
        callApi(props.updateoperationdata, insert.value);
      } else {
        callApi(props.addoperationdata, insert.value);
      }
  }

  onMounted(() => {
    eventBus.$on(props.id + "_" + insertOrUpdateFlagKey, (data) => {
      console.log('insertOrUpdateFlagKey:' + JSON.stringify(data));
      insert.value = data.flag;
      id.value = data.id;
    })

  })
  onUnmounted(() => {
    eventBus.$off(props.id + "_" + insertOrUpdateFlagKey);
  })
</script>

<style scoped>

</style>
